package org.ym.tools.adapter;

import com.google.gson.TypeAdapter;
import com.google.gson.internal.ObjectConstructor;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Collection;

/**
 * @author ym
 */
public class CollectionTypeAdapter<E> extends TypeAdapter<Collection<E>> {

    private TypeAdapter<E> elementTypeAdapter;

    private ObjectConstructor<Collection<E>> objectConstructor;

    public CollectionTypeAdapter(E type,TypeAdapter<E> elementTypeAdapter, ObjectConstructor<Collection<E>> objectConstructor){
        this.elementTypeAdapter = elementTypeAdapter;
        this.objectConstructor = objectConstructor;
    }

    @Override
    public void write(JsonWriter out, Collection<E> collection) throws IOException {
        if (collection == null) {
            out.nullValue();
            return;
        }
        out.beginArray();
        for (E element : collection) {
            elementTypeAdapter.write(out, element);
        }
        out.endArray();
    }

    @Override
    public Collection<E> read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }else if(in.peek() == JsonToken.STRING){
            in.nextString();
            return objectConstructor.construct();
        }
        Collection<E> collection = objectConstructor.construct();
        in.beginArray();
        while (in.hasNext()) {
            E instance = elementTypeAdapter.read(in);
            collection.add(instance);
        }
        in.endArray();
        return collection;
    }
}
